﻿using Common.Dtos;
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using Sigma.Admin.Client.DialogAware;
using Sigma.Admin.Client.Extensions;
using Sigma.Admin.Client.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sigma.Admin.Client.ViewModels.DialogVM
{
    public class AddUserViewModel : BindableBase, IDialogHostAware
    {
        private readonly IUserService _userService;
        private readonly IEventAggregator _ea;
        public string DialogHostName { get; set; }
        public DelegateCommand SaveCommand { get; set; }
        public DelegateCommand CancelCommand { get; set; }

        public AddUserViewModel(IUserService service, IEventAggregator ea)
        {
            _userService = service;
            SaveCommand = new DelegateCommand(Save);
            CancelCommand = new DelegateCommand(Cancel);
            _ea = ea;
        }

        private UsersDto userDto=new UsersDto();

        public UsersDto UserDto
        {
            get { return userDto; }
            set { userDto = value; RaisePropertyChanged(); }
        }
        #region 显示加载
        private bool _isLoading = false;
        public bool IsLoading
        {
            get { return _isLoading; }
            set { _isLoading = value; RaisePropertyChanged(); }
        }
        public void OnLoading()
        {
            IsLoading = true;
        }
        public void UnLoading()
        {
            IsLoading = false;
        }
        #endregion
        private void Cancel()
        {
            if (DialogHost.IsDialogOpen(DialogHostName))
                DialogHost.Close(DialogHostName, new DialogResult(ButtonResult.No));
        }

        private async void Save()
        {
            if (string.IsNullOrWhiteSpace(userDto.UserName) || string.IsNullOrWhiteSpace(userDto.Account) || string.IsNullOrWhiteSpace(userDto.PassWord))
                return;
            OnLoading();
            if (DialogHost.IsDialogOpen(DialogHostName))
            {
                var res = await _userService.AddUser(UserDto);
                if (res.Status)
                {
                    DialogHost.Close(DialogHostName, new DialogResult(ButtonResult.OK));
                    _ea.SendMessage(res.Message ?? "响应成功");
                }
                else
                {
                    _ea.SendMessage(res.Message??"服务器无响应", "AddUser");
                }

            }
            UnLoading();
        }

        public void OnDialogOpend(IDialogParameters parameters)
        {
           
        }
        
    }
}
